<?php

namespace App\Helper;

use App\Models\V1\Pay\OfflineCompanyAccount;
use App\Models\V1\Pay\PaymentAccount;
use App\Models\V1\Pay\PaymentChannel;
use Illuminate\Support\Facades\Cache;
use Alipay\EasySDK\Kernel\Config;
use Alipay\EasySDK\Kernel\Factory as AlipayFactory;
use EasyWeChat\Factory as WechatFactory;
/**
 * 支付方式
 */
class PayHelper
{
    protected $config=null;
    public function __construct()
    {

    }

    /**
     * 进行实际支付流程
     * @return void
     */
    public static function goPay($order=[],$type="balance"){
        switch ($order->payment_code){
            case "alipay_app"://支付宝APP
                return self::alipay($order,$type);
            case "wechat_app"://微信APP
                return self::wechat($order,$type);
            default:

                break;
        }
        return ['code'=>300,"message"=>"未知的支付方式"];
    }

    /**
     * 支付宝支付
     * @param $order
     * @return array|void
     */
    private function alipay($order=[],$type="balance"){
        try {
            $options = new Config();
            $options->protocol = 'https';
            $options->gatewayHost = 'openapi.alipay.com';
            $options->signType = 'RSA2';

            $options->appId = get_setting('alipay_appId');
            // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
            $options->merchantPrivateKey = get_setting('alipay_PrivateKey');


            //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
            $options->alipayPublicKey = get_setting('alipay_PublicKey');
            //可设置异步通知接收服务地址（可选）
            $options->notifyUrl = url('v1/api/notify/alipay/'.$type);

            //可设置AES密钥，调用AES加解密相关接口时需要（可选）
            $options->encryptKey = "";
            AlipayFactory::setOptions($options);

            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
            $result = AlipayFactory::payment()->app()->pay($order->order_sn, $order->order_sn, $order->money);
            //3. 处理响应或异常
            if (!empty($result->body)) {
                return ['code'=>200,"data"=>$result->body];
            }
        } catch (Exception $e) {
            return ['code'=>300,"message"=>$e->getMessage()];
        }
    }

    /**
     * 微信支付
     * @param $order
     * @return void
     */
    private function wechat($order=[],$type="balance"){
        try {
            $config = [
                // 必要配置
                'app_id'             => get_setting('wechat_appId'),
                'mch_id'             => get_setting('wechat_mchId'),
                'key'                => get_setting('wechat_key'),   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
                'notify_url'         => url('v1/api/notify/wechat/'.$type),     // 你也可以在下单时单独设置来想覆盖它
            ];

            $app = WechatFactory::payment($config);
            $result = $app->order->unify([
                'body' => $order->order_sn,
                'out_trade_no' => $order->order_sn,
                'total_fee' => $order->money*100,
                'trade_type' => 'APP', // 请对应换成你的支付方式对应的值类型
            ]);

            //如trade_type = APP
            //需要进行二次签名
            $data=(new \EasyWeChat\Payment\Jssdk\Client($app))->appConfig($result['prepay_id']);
            return ['code'=>200,"data"=>$data];
        }catch (\Exception $e){
            return ['code'=>300,"message"=>$e->getMessage()];
        }
    }
}
